package com.easy.zhihu.util;


import com.huaban.analysis.jieba.WordDictionary;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * @Packge com.easy.zhihu.util
 * @Autor linNaibin
 * @Description
 * @Version 1.0
 * @Date 2021/3/19 14:55
 */
public class LoadDic {

    private LoadDic() {
        this.init();
    }

    private static LoadDic singleton;

    public static LoadDic getInstance() {
        if (singleton == null) {
            synchronized (LoadDic.class) {
                if (singleton == null) {
                    singleton = new LoadDic();
                    return singleton;
                }
            }
        }
        return singleton;
    }

    public static void main(String[] args) {
        LoadDic dic = new LoadDic();
        Map<String, Integer> city = new HashMap<>();
        dic.loadDict("/city.dic", city);
        System.out.println("xx");
    }

    public static Map<String, Integer> CITY = new HashMap<>();
    public static Map<String, Integer> ZY = new HashMap<>();
    public static Map<String, Integer> XL = new HashMap<>();
    public static Map<String, Integer> NL = new HashMap<>();

    private void init() {
        loadDict("/city.dic", CITY);
        loadDict("/xl.dic", XL);
        loadDict("/zy.dic", ZY);

    }


    public void loadDict(String dicUrl, Map<String, Integer> map) {
        InputStream is = this.getClass().getResourceAsStream(dicUrl);
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));

            long s = System.currentTimeMillis();
            while (br.ready()) {
                String line = br.readLine();
                map.put(line, 1);
            }
            // normalize

            System.out.println(String.format(Locale.getDefault(), "main dict load finished, time elapsed %d ms",
                    System.currentTimeMillis() - s));
        } catch (IOException e) {
            System.err.println(String.format(Locale.getDefault(), "%s load failure!", dicUrl));
        } finally {
            try {
                if (null != is)
                    is.close();
            } catch (IOException e) {
                System.err.println(String.format(Locale.getDefault(), "%s close failure!", dicUrl));
            }
        }
    }

}
